package com.hepinghospital.user.ui.activity.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.ui.PayActivity;
import com.hepinghospital.user.ui.activity.graphic.graphicSelect.GraphicSelectActivity;
import com.hepinghospital.user.ui.widget.CustomPopWindow;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.CloudDoctorResponse;
import com.rest.response.DicResponse;
import com.rest.response.Doctor;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.DpUtil;
import jz.joyoung.robot.util.SoftKeyboardUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilString;


/**
 * @Description: 首页搜索
 * @Author: lzp
 * @CreateDate: 2022/4/28 14:49
 * @UpdateRemark:
 */
public class SearchDoctorActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.doctor_recyclerView)
    RecyclerView rvDoctor;
    @BindView(R.id.edt_search)
    EditText edtSearch;
    @BindView(R.id.tv_keshi)
    TextView tvKeshi;
    @BindView(R.id.tv_zhichen)
    TextView tvZhichen;
    @BindView(R.id.tv_chufang)
    TextView tvChufang;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.icon1)
    ImageView icon1;
    @BindView(R.id.icon2)
    ImageView icon2;
    @BindView(R.id.icon3)
    ImageView icon3;
    @BindView(R.id.icon4)
    ImageView icon4;
    @BindView(R.id.btn_type)
    LinearLayout llType;
    List<DicResponse> list = new ArrayList<>();
    List<Doctor> doctorList = new ArrayList<>();
    /**
     * 0:图文咨询和云门诊
     * 1：图文咨询
     * 3:云门诊
     * 4 门诊挂号
     */
    int diagType;
    int current = 1;
    String searchContent = "", codeType = "", codeServiceType = "", deptId = "", code = "", isPrescription = "", deptName = "", checkDetailId;

    private DoctorAdapter doctorAdapter;
    private AddMedicineAdapter adapter;
    private CustomPopWindow mPopWindow;


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_search_doctor;
    }

    @Override
    protected void initViews() {
        if (diagType == 1) {
            tvTitle.setText("图文问诊");
        } else if (diagType == 4) {
            tvTitle.setText("门诊预约");
        } else {
            tvTitle.setText("全部医生");
        }
        rvDoctor.setLayoutManager(new LinearLayoutManager(this));
        doctorAdapter = new DoctorAdapter();
        rvDoctor.setAdapter(doctorAdapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            current = 1;
            queryDoctors(deptId, searchContent, isPrescription);
        });
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            current++;
            queryDoctors(deptId, searchContent, isPrescription);
        });
        edtSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                // 按下完成按钮，这里和上面imeOptions对应
                searchContent = edtSearch.getText().toString();
                current = 1;
                queryDoctors(deptId, searchContent, isPrescription);
                SoftKeyboardUtil.hideSoftKeyboard(SearchDoctorActivity.this);
            }
            return false;
        });
    }

    @Override
    protected void initData() {
        diagType = getIntent().getIntExtra("type", -1);
        deptName = getIntent().getStringExtra("deptName");
        checkDetailId = getIntent().getStringExtra("checkDetailId");

        //图文咨询,门诊挂号，和云门诊，没有服务类型
        if (diagType == 0) {
            llType.setVisibility(View.VISIBLE);
        } else {
            llType.setVisibility(View.GONE);
        }
        if (!UtilString.isEmpty(deptName)) {
            //从科室过来的,选中科室
            deptId = getIntent().getStringExtra("deptId");
            tvZhichen.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
            tvKeshi.setTextColor(ContextCompat.getColor(this, R.color.color_5481fa));
            tvType.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
            tvChufang.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
            tvKeshi.setTypeface(Typeface.DEFAULT_BOLD);
            tvKeshi.setText(deptName);
        }
        queryDoctors(deptId, searchContent, isPrescription);
    }

    /**
     * 医生列表
     *
     * @time 2020/5/11 16:00
     */
    class DoctorAdapter extends RecyclerView.Adapter<DoctorAdapter.Holder> {

        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(SearchDoctorActivity.this).inflate(R.layout.item_seach_doctor, parent, false));
            return myHolder;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                if (diagType == 0 || diagType == 4) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", doctorList.get(position).id);
                    bundle.putInt(UIConstants.DOCTORDETAILACTIVITY_TYPE_FLAG, UIConstants.DOCTORDETAILACTIVITY_TYPE_0);
                    startActivity(DoctorDetailActivity.class, bundle);
                } else if (diagType == 1) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(UIConstants.OBJ_Doctor, doctorList.get(position));
                    bundle.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_0);
                    bundle.putString("checkDetailId", checkDetailId);
                    startActivity(GraphicSelectActivity.class, bundle);
                } else if (diagType == 3) {
                    Bundle bundleCloud = new Bundle();
                    bundleCloud.putSerializable(UIConstants.OBJ_Doctor, doctorList.get(position));
                    bundleCloud.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_1);
                    startActivity(PayActivity.class, bundleCloud);
                }
            });
            holder.tv_level.setText(doctorList.get(position).jobTitleName);
            holder.tv_skill.setText("擅长:" + doctorList.get(position).docGoodAtNames);
            holder.tv_star.setText(doctorList.get(position).score);
            holder.tv_name.setText(doctorList.get(position).docName);
            ImageLoaderHelper.getInstance().GlideCircleImageLoader(SearchDoctorActivity.this, doctorList.get(position).thumbnailUrl, holder.img_head);
            if (doctorList.get(position).isPrescription == 1) {
                holder.tv_recipel.setText("处方");
                holder.tv_recipel.setVisibility(View.VISIBLE);
//                holder.tv_recipel.setTextColor(Color.parseColor("#FFFFFF"));
            } else {
                holder.tv_recipel.setText("非处方");
                holder.tv_recipel.setVisibility(View.GONE);
//                holder.tv_recipel.setTextColor(Color.parseColor("#ffd5d5d5"));
            }
            if (!UtilString.isEmpty(doctorList.get(position).num + "")) {
                holder.tv_turnNum.setVisibility(View.VISIBLE);
                holder.tv_turnNum.setText("" + doctorList.get(position).num);
            } else {
                holder.tv_turnNum.setVisibility(View.GONE);
            }
            if (!UtilString.isEmpty(doctorList.get(position).deptName)) {
                holder.tv_deptName.setText(doctorList.get(position).deptName);
            } else {
                holder.tv_deptName.setVisibility(View.GONE);
            }
            holder.tvRecommend.setVisibility(View.GONE);
//            if ("0".equals(doctorList.get(position).isRecommend)) {
//                holder.tvRecommend.setVisibility(View.GONE);
//            } else {
//                holder.tvRecommend.setVisibility(View.VISIBLE);
//            }
            holder.tv_star.setText(doctorList.get(position).score);
//            holder.ratingBar.setRating(Float.parseFloat(doctorList.get(position).score));
            holder.btn_yuyue.setOnClickListener(v -> {
                Bundle bundleCloud = new Bundle();
                bundleCloud.putSerializable(UIConstants.OBJ_Doctor, doctorList.get(position));
                bundleCloud.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_1);
                startActivity(PayActivity.class, bundleCloud);
            });
            holder.btn_zixun.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putSerializable(UIConstants.OBJ_Doctor, doctorList.get(position));
                bundle.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_0);
                startActivity(GraphicSelectActivity.class, bundle);
            });

            //0:图文咨询和云门诊 1：图文咨询 3:云门诊 4 门诊挂号
            if (diagType == 0 || diagType == 4) {
                if (doctorList.get(position).diagType == 0) {
                    holder.btn_yuyue.setVisibility(View.VISIBLE);
                    holder.btn_zixun.setVisibility(View.VISIBLE);
                } else if (doctorList.get(position).diagType == 1) {
                    holder.btn_yuyue.setVisibility(View.GONE);
                    holder.btn_zixun.setVisibility(View.VISIBLE);
                } else if (doctorList.get(position).diagType == 3) {
                    holder.btn_yuyue.setVisibility(View.VISIBLE);
                    holder.btn_zixun.setVisibility(View.GONE);
                } else {
                    holder.btn_yuyue.setVisibility(View.GONE);
                    holder.btn_zixun.setVisibility(View.GONE);
//                    holder.btn_yuyue.setVisibility(View.INVISIBLE);
//                    holder.btn_zixun.setVisibility(View.INVISIBLE);
                }
            } else {
                holder.btn_yuyue.setVisibility(View.GONE);
                holder.btn_zixun.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return doctorList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_level, tv_recipel, tv_deptName, tv_skill, tv_star, btn_yuyue, btn_zixun, tv_turnNum, tvRecommend;
            ImageView img_head;
            RatingBar ratingBar;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_level = itemView.findViewById(R.id.tv_level);
                tv_recipel = itemView.findViewById(R.id.tv_recipel);
                tv_deptName = itemView.findViewById(R.id.tv_deptName);
                tv_skill = itemView.findViewById(R.id.tv_skill);
                tv_star = itemView.findViewById(R.id.tv_star);
                img_head = itemView.findViewById(R.id.img_head);
                btn_yuyue = itemView.findViewById(R.id.btn_yuyue);
                btn_zixun = itemView.findViewById(R.id.btn_zixun);
                tv_turnNum = itemView.findViewById(R.id.tv_turn_num);
                tvRecommend = itemView.findViewById(R.id.iv_recommend);
            }
        }
    }

    private void queryDoctors(String deptId, String content, String isPrescription) {
        RestProxy.getInstance().queryDoctors(content, deptId, diagType + "", code, isPrescription, current + "", "10", new BaseObserver<CloudDoctorResponse>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                ToastUtil.onError(mContext, e);
                if (current == 1) {
                    refreshLayout.finishRefresh(true);
                } else {
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onSuccess(CloudDoctorResponse result) {
                if (current == 1) {
                    doctorList.clear();
                    doctorList.addAll(result.records);
                    refreshLayout.finishRefresh(true);
                    if (result.records.size() < 10) {
                        refreshLayout.setEnableLoadMore(false);
                    } else {
                        refreshLayout.setEnableLoadMore(true);
                    }
                } else {
                    if (result.records.size() == 0) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                        return;
                    }
                    doctorList.addAll(result.records);
                    refreshLayout.finishLoadMore();
                }
                doctorAdapter.notifyDataSetChanged();
            }
        });
    }

    @OnClick(R.id.btn_keshi)
    void btn_keshi() {
        tvZhichen.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvKeshi.setTextColor(ContextCompat.getColor(this, R.color.color_5481fa));
        tvType.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvChufang.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvZhichen.setTypeface(Typeface.DEFAULT);
        tvKeshi.setTypeface(Typeface.DEFAULT);
        tvType.setTypeface(Typeface.DEFAULT);
        tvChufang.setTypeface(Typeface.DEFAULT);
        showPopListView(tvKeshi, 0);
    }

    @OnClick(R.id.btn_zhichen)
    void btn_zhichen() {
        tvZhichen.setTextColor(ContextCompat.getColor(this, R.color.color_5481fa));
        tvKeshi.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvType.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvChufang.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvZhichen.setTypeface(Typeface.DEFAULT);
        tvKeshi.setTypeface(Typeface.DEFAULT);
        tvType.setTypeface(Typeface.DEFAULT);
        tvChufang.setTypeface(Typeface.DEFAULT);
        showPopListView(tvZhichen, 1);

    }

    @OnClick(R.id.btn_chufang)
    void tv_chufang() {
        tvZhichen.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvKeshi.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvType.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvChufang.setTextColor(ContextCompat.getColor(this, R.color.color_5481fa));
        tvZhichen.setTypeface(Typeface.DEFAULT);
        tvKeshi.setTypeface(Typeface.DEFAULT);
        tvType.setTypeface(Typeface.DEFAULT);
        tvChufang.setTypeface(Typeface.DEFAULT);
        showPopListView(tvChufang, 2);
    }

    @OnClick(R.id.btn_type)
    void tv_type() {
        tvZhichen.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvKeshi.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvType.setTextColor(ContextCompat.getColor(this, R.color.color_5481fa));
        tvChufang.setTextColor(ContextCompat.getColor(this, R.color.lightBlack));
        tvZhichen.setTypeface(Typeface.DEFAULT);
        tvKeshi.setTypeface(Typeface.DEFAULT);
        tvType.setTypeface(Typeface.DEFAULT);
        tvChufang.setTypeface(Typeface.DEFAULT);
        showPopListView(tvType, 3);
    }

    private void showPopListView(View view, int type) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_window, null);
        RecyclerView recyclerView = contentView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AddMedicineAdapter(this, type);
        recyclerView.setAdapter(adapter);
        if (type == 0) {
            //按照科室
            getDepartmentList();
        } else if (type == 1) {
            //职称信息
            getDictList();
        } else if (type == 2) {
            list.clear();
            list.add(new DicResponse("全部", "0"));
            list.add(new DicResponse("处方", "1"));
            list.add(new DicResponse("非处方", "2"));
            adapter.notifyDataSetChanged();
        } else {
            list.clear();
            list.add(new DicResponse("全部", "0"));
            list.add(new DicResponse("图文问诊", "1"));
            list.add(new DicResponse("云门诊", "2"));
            list.add(new DicResponse("门诊挂号", "3"));
            adapter.notifyDataSetChanged();
        }

        //创建并显示popWindow
        mPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .setTouchable(true)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, DpUtil.dip2px(this, 300))
                .create()
                .showAsDropDown(view, 0, 0, Gravity.CENTER);
    }

    class AddMedicineAdapter extends RecyclerView.Adapter<AddMedicineAdapter.Holder> {

        int type;
        private Context context;

        AddMedicineAdapter(Context context, int type) {
            this.context = context;
            this.type = type;
        }

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(context).inflate(R.layout.item_textview, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {

            holder.tv_name.setText(list.get(position).name);
            if (list.get(position).name.equals(deptName) && !list.get(position).name.equals("全部")) {
                Log.e("每一项id---", list.get(position).name);
                //和上次选中的一样，字体是蓝色
                holder.tv_name.setTextColor(ContextCompat.getColor(context, R.color.color_5481fa));
            } else {
                holder.tv_name.setTextColor(ContextCompat.getColor(context, R.color.commonBlack));
            }

            holder.itemView.setOnClickListener(v -> {
                if (type == 0) {
                    //按照科室查询
                    if (position == 0) {
                        deptId = "";
                        tvKeshi.setText("科室");
                        tvKeshi.setTextColor(ContextCompat.getColor(mContext, R.color.lightBlack));
                        tvKeshi.setTypeface(Typeface.DEFAULT);
                    } else {
                        tvKeshi.setText(list.get(position).name);
                        deptId = list.get(position).id;
                        deptName = list.get(position).name;
                        tvKeshi.setTypeface(Typeface.DEFAULT_BOLD);
                        tvKeshi.setTextColor(ContextCompat.getColor(context, R.color.color_5481fa));
                    }
                    current = 1;
                    queryDoctors(deptId, searchContent, isPrescription);
                    mPopWindow.dissmiss();
                } else if (type == 1) {
                    //点击的职称查询
                    if (position == 0) {
                        code = "";
                        tvZhichen.setText("职称");
                        tvZhichen.setTextColor(ContextCompat.getColor(mContext, R.color.lightBlack));
                        tvZhichen.setTypeface(Typeface.DEFAULT);
                    } else {
                        code = list.get(position).code;
                        tvZhichen.setText(list.get(position).name);
                        tvZhichen.setTypeface(Typeface.DEFAULT_BOLD);
                        tvZhichen.setTextColor(ContextCompat.getColor(context, R.color.color_5481fa));
                    }
                    current = 1;
                    queryDoctors(deptId, searchContent, isPrescription);
                    mPopWindow.dissmiss();
                } else if (type == 2) {
                    codeType = list.get(position).code;
                    if ("1".equals(codeType)) {
                        tvChufang.setTextColor(ContextCompat.getColor(context, R.color.color_5481fa));
                        tvChufang.setText("处方");
                        isPrescription = "1";
                        tvChufang.setTypeface(Typeface.DEFAULT_BOLD);
                    } else if ("2".equals(codeType)) {
                        tvChufang.setTextColor(ContextCompat.getColor(context, R.color.color_5481fa));
                        tvChufang.setText("非处方");
                        isPrescription = "0";
                        tvChufang.setTypeface(Typeface.DEFAULT_BOLD);
                    } else {
                        tvChufang.setText("处方权限");
                        tvChufang.setTextColor(ContextCompat.getColor(context, R.color.lightBlack));
                        isPrescription = "";
                    }
                    current = 1;
                    queryDoctors(deptId, searchContent, isPrescription);
                    mPopWindow.dissmiss();
                } else {
                    codeServiceType = list.get(position).code;
                    if ("1".equals(codeServiceType)) {
                        tvType.setTextColor(ContextCompat.getColor(context, R.color.color_5481fa));
                        tvType.setText("图文问诊");
                        diagType = 1;
                        tvType.setTypeface(Typeface.DEFAULT_BOLD);
                    } else if ("2".equals(codeServiceType)) {
                        tvType.setTextColor(ContextCompat.getColor(context, R.color.color_5481fa));
                        tvType.setText("云门诊");
                        diagType = 3;
                        tvType.setTypeface(Typeface.DEFAULT_BOLD);
                    } else if ("3".equals(codeServiceType)) {
                        tvType.setTextColor(ContextCompat.getColor(context, R.color.color_5481fa));
                        tvType.setText("门诊挂号");
                        diagType = 4;
                        tvType.setTypeface(Typeface.DEFAULT_BOLD);
                    } else {
                        tvType.setText("服务类型");
                        tvType.setTextColor(ContextCompat.getColor(context, R.color.lightBlack));
                        diagType = 0;
                    }
                    current = 1;
                    queryDoctors(deptId, searchContent, isPrescription);
                    mPopWindow.dissmiss();
                }
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.text);
            }
        }
    }

    private void getDictList() {
        RestProxy.getInstance().getDicList(new BaseObserver<List<DicResponse>>() {

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(SearchDoctorActivity.this, e);
            }

            @Override
            public void onSuccess(List<DicResponse> result) {
                list.clear();
                list.add(new DicResponse("全部", ""));
                list.addAll(result);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void getDepartmentList() {
        RestProxy.getInstance().getDepartment2List(new Observer<List<DicResponse>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<DicResponse> dicResponses) {
                list.clear();
                list.add(new DicResponse("全部", ""));
                list.addAll(dicResponses);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                refreshLayout.finishRefresh(false);
                ToastUtil.onError(SearchDoctorActivity.this, e);

            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }
}
